package cn.web.tunnelrobot.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 发送手机验证码
 * @author lichuang
 * 
 */
public class SendPhoneCode {
	public static String  verPhoneCode = "";
	/**
	 * 生成4位验证码
	 */
	public static String getCheckCode() {
		// qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGJKLZXCVBNM
		String ZiMu = "1234567890";
		String result = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			int index = random.nextInt(ZiMu.length());
			char c = ZiMu.charAt(index);
			result += c;
		}
		System.out.println("随机生成的验证码是:"+result);
		return result;

	}
	/**
	 * 发送验证码
	 * @param phone
	 */
	public static int send(String phone) {
		verPhoneCode = getCheckCode();//获取验证码
		int consequence = 0;
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod("http://gbk.api.smschinese.cn");
		post.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=gbk");//
		NameValuePair[] data = { new NameValuePair("Uid", "人美国文"),
				new NameValuePair("Key", "renwen1234567890"),
				new NameValuePair("smsMob", phone),
				new NameValuePair("smsText", "您的验证码是:" + verPhoneCode)
		};
		System.out.println("短信返送成功!接收电话:"+phone+",验证码是:"+verPhoneCode);
		post.setRequestBody(data);
		try {
			client.executeMethod(post);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		int statusCode = post.getStatusCode();
		System.out.println("statusCode:" + statusCode);
		String result;
		try {
			result = new String(post.getResponseBodyAsString().getBytes("gbk"));
			System.out.println(result);
			consequence = 1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		post.releaseConnection();
		return consequence;
	}
}
